# Chapter1_Level1.gd - 第一章第一关脚本
# 《光影之间》- 孤独觉醒

extends Node2D

# 关卡信息
@export var level_name := "孤独觉醒"
@export var chapter := 1
@export var level_number := 1

# 关卡状态
var level_completed := false
var tutorial_completed := false
var shadow_vision_taught := false

# 节点引用
@onready var energy_bar = $UI/EnergyBar
@onready var player: CharacterBody2D = $GameObjects/Player
@onready var spawn_point: Marker2D = $GameObjects/SpawnPoint
@onready var exit_point: Area2D = $GameObjects/ExitPoint
@onready var level_title: Label = $UI/LevelUI/LevelTitle
@onready var instructions: Label = $UI/LevelUI/Instructions
@onready var main_light: PointLight2D = $Lighting/MainLight
@onready var secondary_light: PointLight2D = $Lighting/SecondaryLight
@onready var shadow_zone1: Area2D = $Lighting/ShadowZone1
@onready var shadow_zone2: Area2D = $Lighting/ShadowZone2
@onready var shadow_vision_effect: ColorRect = $ShadowVisionLayer/ShadowVisionEffect

# 教学步骤
enum TutorialStep {
	MOVEMENT,
	JUMPING,
	SHADOW_VISION,
	LIGHT_INTERACTION,
	COMPLETED
}

var current_tutorial_step := TutorialStep.MOVEMENT
var tutorial_timer := 0.0
var instruction_display_time := 3.0

# 信号
signal level_completed_signal
signal tutorial_step_completed(step: TutorialStep)

func _ready():
	print("第一章第一关已加载: ", level_name)
	setup_level()
	start_tutorial()
	setup_shadow_vision_effect()
	
	# 连接信号
	if player:
		player.energy_changed.connect(_on_player_energy_changed)
		player.shadow_vision_toggled.connect(_on_player_shadow_vision_toggled)
		player.player_moved.connect(_on_player_moved)
		player.player_jumped.connect(_on_player_jumped)
	
	# 注册光照系统
	if LightingSystem:
		LightingSystem.register_light_source(main_light)
		LightingSystem.register_light_source(secondary_light)
		LightingSystem.register_shadow_zone(shadow_zone1)
		LightingSystem.register_shadow_zone(shadow_zone2)

func _process(delta):
	tutorial_timer += delta
	update_tutorial()

func _on_player_energy_changed(current_energy: float, max_energy: float):
	# 更新能量条
	energy_bar.value = current_energy
	energy_bar.max_value = max_energy
	
# 设置关卡
func setup_level():
	# 设置玩家位置
	if player and spawn_point:
		player.global_position = spawn_point.global_position
	
	# 设置关卡标题显示
	if level_title:
		level_title.text = level_name
		# 3秒后隐藏标题
		var tween = create_tween()
		tween.tween_interval(3.0)
		tween.tween_property(level_title, "modulate:a", 0.0, 1.0)
	
	# 设置游戏状态
	if GameState:
		GameState.set_current_level(chapter, level_number)

# 设置影视效果
func setup_shadow_vision_effect():
	# 创建shader材质
	var shader_material = ShaderMaterial.new()
	var shader = load("res://shaders/shadow_vision.gdshader")
	shader_material.shader = shader
	
	# 设置shader参数 - 默认状态为黑暗（is_active = false）
	shader_material.set_shader_parameter("is_active", false)
	shader_material.set_shader_parameter("intensity", 0.8)
	shader_material.set_shader_parameter("contrast", 2.0)
	shader_material.set_shader_parameter("tint_color", Color(0.2, 0.2, 0.8, 0.0))
	
	# 应用材质到影视效果节点
	if shadow_vision_effect:
		shadow_vision_effect.material = shader_material

# 开始教学
func start_tutorial():
	current_tutorial_step = TutorialStep.MOVEMENT
	tutorial_timer = 0.0
	show_tutorial_instruction("使用 A/D 键左右移动")

# 更新教学
func update_tutorial():
	match current_tutorial_step:
		TutorialStep.MOVEMENT:
			if tutorial_timer > 5.0:  # 5秒后自动进入下一步
				advance_tutorial_step()
		
		TutorialStep.JUMPING:
			if tutorial_timer > 5.0:
				advance_tutorial_step()
		
		TutorialStep.SHADOW_VISION:
			if tutorial_timer > 8.0:
				advance_tutorial_step()
		
		TutorialStep.LIGHT_INTERACTION:
			if tutorial_timer > 10.0:
				advance_tutorial_step()

# 推进教学步骤
func advance_tutorial_step():
	tutorial_step_completed.emit(current_tutorial_step)
	
	match current_tutorial_step:
		TutorialStep.MOVEMENT:
			current_tutorial_step = TutorialStep.JUMPING
			show_tutorial_instruction("按 W 键或空格键跳跃")
		
		TutorialStep.JUMPING:
			current_tutorial_step = TutorialStep.SHADOW_VISION
			show_tutorial_instruction("按 V 键激活影视能力，观察隐藏的路径")
		
		TutorialStep.SHADOW_VISION:
			current_tutorial_step = TutorialStep.LIGHT_INTERACTION
			show_tutorial_instruction("靠近光源感受温暖，进入阴影区域隐藏")
		
		TutorialStep.LIGHT_INTERACTION:
			current_tutorial_step = TutorialStep.COMPLETED
			show_tutorial_instruction("很好！现在前往右侧的出口")
			tutorial_completed = true
	
	tutorial_timer = 0.0

# 显示教学指令
func show_tutorial_instruction(text: String):
	if instructions:
		instructions.text = text
		instructions.modulate.a = 1.0
		
		# 创建淡入淡出效果
		var tween = create_tween()
		tween.tween_property(instructions, "modulate:a", 1.0, 0.5)
		tween.tween_interval(instruction_display_time)
		tween.tween_property(instructions, "modulate:a", 0.3, 0.5)

# 玩家移动事件
func _on_player_moved():
	if current_tutorial_step == TutorialStep.MOVEMENT:
		advance_tutorial_step()

# 玩家跳跃事件
func _on_player_jumped():
	if current_tutorial_step == TutorialStep.JUMPING:
		advance_tutorial_step()

# 玩家激活影视能力事件
func _on_player_shadow_vision_toggled(is_active: bool):
	print("Chapter1_Level1: _on_player_shadow_vision_toggled called with is_active: ", is_active)
	if shadow_vision_effect and shadow_vision_effect.material:
		shadow_vision_effect.material.set_shader_parameter("is_active", is_active)
		print("Chapter1_Level1: Shader parameter is_active set to ", is_active)
	else:
		print("Chapter1_Level1: shadow_vision_effect or its material is null!")
	
	if is_active:
		print("影视能力已激活")
	else:
		print("影视能力已关闭")
	
	if current_tutorial_step == TutorialStep.SHADOW_VISION and is_active:
		shadow_vision_taught = true
		advance_tutorial_step()

# 出口触发事件
func _on_exit_point_body_entered(body):
	if body == player and tutorial_completed:
		complete_level()

# 完成关卡
func complete_level():
	if level_completed:
		return
	
	level_completed = true
	print("关卡完成: ", level_name)
	
	# 更新游戏状态
	if GameState:
		# 将章节和关卡转换为唯一的关卡编号，并传递完成数据
		var level_id = chapter * 10 + level_number
		var completion_data = {
			"chapter": chapter,
			"level": level_number,
			"completed_time": Time.get_unix_time_from_system(),
			"tutorial_completed": tutorial_completed,
			"shadow_vision_taught": shadow_vision_taught
		}
		GameState.complete_level(level_id, completion_data)
		GameState.set_story_flag("chapter1_level1_completed", true)
	
	# 显示完成信息
	show_tutorial_instruction("关卡完成！正在加载下一关...")
	
	# 发送完成信号
	level_completed_signal.emit()
	
	# 延迟后切换到下一关
	await get_tree().create_timer(2.0).timeout
	load_next_level()

# 加载下一关
func load_next_level():
	# 这里可以加载下一关或返回主菜单
	print("准备加载下一关...")
	# get_tree().change_scene_to_file("res://scenes/levels/Chapter1_Level2.tscn")

# 重置关卡
func reset_level():
	level_completed = false
	tutorial_completed = false
	shadow_vision_taught = false
	current_tutorial_step = TutorialStep.MOVEMENT
	tutorial_timer = 0.0
	
	# 重置玩家位置
	if player and spawn_point:
		player.global_position = spawn_point.global_position
		player.reset_player_state()
	
	# 重新开始教学
	start_tutorial()

# 获取关卡进度
func get_level_progress() -> Dictionary:
	return {
		"level_name": level_name,
		"chapter": chapter,
		"level_number": level_number,
		"completed": level_completed,
		"tutorial_completed": tutorial_completed,
		"shadow_vision_taught": shadow_vision_taught,
		"current_tutorial_step": current_tutorial_step
	}

# 设置关卡进度
func set_level_progress(progress: Dictionary):
	if progress.has("completed"):
		level_completed = progress.completed
	if progress.has("tutorial_completed"):
		tutorial_completed = progress.tutorial_completed
	if progress.has("shadow_vision_taught"):
		shadow_vision_taught = progress.shadow_vision_taught
	if progress.has("current_tutorial_step"):
		current_tutorial_step = progress.current_tutorial_step

# 暂停关卡
func pause_level():
	get_tree().paused = true

# 恢复关卡
func resume_level():
	get_tree().paused = false

# 获取关卡统计
func get_level_stats() -> Dictionary:
	return {
		"completion_time": tutorial_timer,
		"tutorial_steps_completed": current_tutorial_step,
		"shadow_vision_used": shadow_vision_taught
	}
